package com.tdk.bts.dao;

import com.tdk.bts.constants.Constants;
import com.tdk.bts.entity.Film;
import com.tdk.bts.entity.FilmScreen;
import com.tdk.bts.entity.Theater;
import com.tdk.bts.util.DruidConnectionUtil;
import com.tdk.bts.util.Request;
import com.tdk.bts.vo.FilmScreenVO;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import javax.swing.*;
import java.sql.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Date;

public class FilmScreenServiceDao {
    private static Connection conn = null;
    private static JdbcTemplate jdbcTemplate=null;

    static {
        if (conn == null) {
            try {
                conn = DruidConnectionUtil.getConnection();
            } catch (SQLException e) {
                e.printStackTrace();
            }

        }
        if(jdbcTemplate ==null){
            jdbcTemplate =DruidConnectionUtil.getJDBCTemplate();
        }

    }

    //分页查询
    public List<FilmScreenVO> findFilmScreen(Request request) throws SQLException {
        List<FilmScreenVO> list = new ArrayList<>();
        FilmScreenVO fs = null;
        String sql = "select screen.id,screen.name,screen.start_time,screen.start_day,theater.id " +
                "from t_film_screen AS screen INNER JOIN t_theater AS theater on screen.theater_id = theater.id LIMIT ?,?";
        PreparedStatement preSt = conn.prepareStatement(sql);
        int m = Integer.parseInt(request.getParameter("pageNo"))-1;
        preSt.setInt(1, m*Constants.PAGE_SIZE);
        preSt.setInt(2,  Constants.PAGE_SIZE);
        ResultSet rs = preSt.executeQuery();
        while (rs.next()) {
            fs = new FilmScreenVO();
            int screenId = rs.getInt("screen.id");
            fs.setScreenId(screenId);
            String screenName = rs.getString("screen.name");
            fs.setScreenName(screenName);
            String startDay = rs.getDate("screen.start_day").toString();
            String startTime = rs.getTime("screen.start_time").toString();
            fs.setTime(startDay+ " " +startTime);
            int theaterId = rs.getInt("theater.id");
            String newTheaterName = FilmScreenServiceDao.findTheaterName(theaterId);
            fs.setTheaterName(newTheaterName);
            list.add(fs);
        }
        DruidConnectionUtil.closeAll(preSt, rs);
        return list;
    }

    //通过theaterId创建新theaterName
    public static String findTheaterName(int theater_id) throws SQLException {
        String sql = "SELECT theater.name " +
                "FROM t_film_screen as screen,t_theater as theater " +
                "WHERE screen.theater_id=theater.id " +
                "AND theater.id=?";
        PreparedStatement preSt = conn.prepareStatement(sql);
        preSt.setInt(1, theater_id);
        ResultSet rs = preSt.executeQuery();
        String name = null;

        while (rs.next()) {
            name = rs.getString("n ame");
        }
        DruidConnectionUtil.closeAll(preSt, rs);
        return name;
    }

    //添加场次
    public void insertScreen(FilmScreen fs) throws SQLException, ParseException {
        boolean flag=true;
        java.sql.Date startDay = new java.sql.Date(fs.getStartDay().getTime());
        Integer filmId = fs.getFilmId();
        long count = findFilmNameByStartDay(startDay,filmId);
        if (count > 0) {
            JOptionPane.showMessageDialog(null, "每日播放不同电影","提示信息", JOptionPane.ERROR_MESSAGE);
            flag=false;
        }
        java.sql.Date startDay1 = new java.sql.Date(fs.getStartDay().getTime());
        String time = fs.getTime();
        SimpleDateFormat sf = new SimpleDateFormat("HH:mm:ss");
        java.sql.Time time1 = new java.sql.Time(sf.parse(time).getTime());
        List<Integer> theater_ids = findTheaterId(startDay1, time1);
        for (int i = 0; i < theater_ids.size(); i++) {
            if (theater_ids.get(i) == fs.getTheaterId()) {
                JOptionPane.showMessageDialog(null, "该时间段正有电影播放，请重新输入播放时间","提示信息", JOptionPane.ERROR_MESSAGE);
                flag=false;
                break;
            }
        }
        if (flag){
            String sql = "INSERT INTO t_film_screen VALUES(NULL,?,?,?,?,?)";
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1, fs.getName());
            ps.setInt(2, fs.getFilmId());
            ps.setDate(3, startDay1);
            ps.setTime(4, time1);
            ps.setInt(5, fs.getTheaterId());
            ps.execute();
            DruidConnectionUtil.closeAll(ps, null);
        }

    }

    public static Long findFilmNameByStartDay(java.sql.Date start_day,int film_id) {
        String sql = "SELECT COUNT(name) FROM t_film_screen WHERE start_day=? AND film_id=?";
        Map<String, Object> map = jdbcTemplate.queryForMap(sql , start_day , film_id);
        Long num = (Long) map.get("COUNT(NAME)");
        return num;
    }

    //通过start_day和start_time获取theaterId
    public static List<Integer> findTheaterId(Date start_day, Time start_time) throws ParseException {
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append(start_day);
        stringBuffer.append(" ");
        stringBuffer.append(start_time);
        StringBuffer stringBuffer1 = new StringBuffer();
        stringBuffer1.append(start_day);
        stringBuffer1.append(" ");
        String s = start_time.toString();
        String[] split = s.split(":");
        StringBuffer start_time1=new StringBuffer();
        for (int i = 0; i < split.length; i++) {
            if (i==0){

                int i1 = Integer.parseInt(split[i]);
                i1+=02;
                String s1 = String.valueOf(i1);
                split[i]=s1;
                if (split[i].length()==1){
                    start_time1.append("0");
                }
                start_time1.append(split[i]);
            }else {
                start_time1.append(":");
                start_time1.append(split[i]);
            }

        }
        stringBuffer1.append(start_time1);
        String sql = "SELECT theater_id FROM t_film_screen \n" +
                "WHERE CONCAT(start_day,' ',start_time) BETWEEN ? AND ? ";

        List<Integer> list = jdbcTemplate.query(sql, new RowMapper<Integer>() {
            @Override
            public Integer mapRow(ResultSet rs, int rowIndex) throws SQLException {
                int theater_id = rs.getInt("theater_id");
                return theater_id;
            }
        } , stringBuffer, stringBuffer1);
        return list;
    }

    public int findScreenCounts(Request request) throws SQLException {
        String sql = "select COUNT(film_id) from t_film_screen where film_id=?";
        PreparedStatement preSt = conn.prepareStatement(sql);
        preSt.setInt(1,Integer.parseInt(request.getParameter("filmId")));
        ResultSet rs = preSt.executeQuery();
        int m = 0;
        while(rs.next()){
            m = rs.getInt("COUNT(film_id)");
        }
        DruidConnectionUtil.closeAll(preSt,rs);
        return m;
    }

    //前台功能：根据电影id查询所有可用放映日期
    public List<String> findDaysById(int filmId) throws SQLException {
        List<String> list = new ArrayList<>();
        long day = System.currentTimeMillis();
        day = (long)(day-1800000L);
        java.util.Date dateTime = new java.util.Date(day);
        SimpleDateFormat simpleFormatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String format = simpleFormatter.format(dateTime);

        String sql = "select start_day from t_film_screen where film_id=? AND CONCAT(start_day,start_time) >=? ";
        PreparedStatement preSt = conn.prepareStatement(sql);
        preSt.setInt(1, filmId);
        preSt.setString(2,format);
        ResultSet rs = preSt.executeQuery();
        while (rs.next()){
                String startDay = rs.getString("start_day");
                list.add(startDay);
        }
        DruidConnectionUtil.closeAll(preSt,rs);
        return list;
    }

    //根据放映日期查询所有场次
    public List<FilmScreen> findFilmScereenByDay(String day, int filmId) throws SQLException {
        List<FilmScreen> list = new ArrayList<>();
        FilmScreen filmScreen =null;
        String sql = "select id,name,film_id,start_day,start_time,theater_id " +
                "from t_film_screen where start_day=?  AND film_id=?";
        PreparedStatement preSt = conn.prepareStatement(sql);
        preSt.setString(1,day);
        preSt.setInt(2,filmId);
        ResultSet rs = preSt.executeQuery();
        while (rs.next()) {

            filmScreen = new FilmScreen();
            int id = rs.getInt("id");
            filmScreen.setId(id);
            String name = rs.getString("name");
            filmScreen.setName(name);
            int film_Id = rs.getInt("film_id");
            filmScreen.setFilmId(film_Id);
            String startTime = rs.getString("start_time");
            filmScreen.setTime(startTime);
            int theaterId = rs.getInt("theater_id");
            filmScreen.setTheaterId(theaterId);
            list.add(filmScreen);

        }
        DruidConnectionUtil.closeAll(preSt,rs);
        return list;
    }

}
